登录 白背景

101. 对称二叉树

https://leetcode.cn/problems/symmetric-tree/

  • 提交时间:2023-02-21 12:32:42
  • 执行用时:40 ms, 在所有 Python3 提交中击败了64.24%的用户
  • 内存消耗:15.1 MB, 在所有 Python3 提交中击败了49.46%的用户
  • 通过测试用例:199 / 199
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if None == root:
            return True
        if None == root.left and None == root.right:
            return True
        if (None == root.left and None != root.right) or (None != root.left and None == root.right):
            return False
        return self.isSymmetricTree(root.left,root.right)
    def isSymmetricTree(self, p: TreeNode, q: TreeNode) -> bool:
        if None == p and None == q:
            return True
        if (None == p and None != q) or (None != p and None == q):
            return False
        if p.val == q.val:
            return self.isSymmetricTree(p.left,q.right) and self.isSymmetricTree(p.right,q.left)
        else:
            return False